package com.tian.producer;

import com.tian.entity.RetryMessage;
import com.tian.enums.RabbitMQConstantEnum;
import com.tian.factory.ApplicationContextFactory;
import com.tian.mapper.RetryMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * {@code @description:} 用户邀请注册发送消息失败再次重发--生产者
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-24 9:19
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class InvitedRegistryProducer {
    @Resource
    private RetryMessageMapper retryMessageMapper;

    public void sendMessage(RetryMessage retryMessage) {
        log.info("邀请用户注册消息重试补发,{}", retryMessage);
        String message = retryMessage.getContent();
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        RabbitTemplate rabbitTemplate = ApplicationContextFactory.getBean(RabbitTemplate.class);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                retryMessage.setStatus(1);
                retryMessageMapper.updateByPrimaryKey(retryMessage);
                log.info("InvitedRegistry ConfirmCallback 关联数据：{},投递成功,确认情况：{}", correlationData, ack);
            } else {
                retryMessage.setRetriedTimes(retryMessage.getRetriedTimes() + 1);
                retryMessageMapper.updateByPrimaryKey(retryMessage);
                log.info("InvitedRegistry ConfirmCallback 关联数据：{},投递失败,确认情况：{}，原因：{}", correlationData, ack, cause);
            }
        });

        rabbitTemplate.setReturnCallback((msg, replyCode, replyText, exchange, routingKey) -> {
            log.info("InvitedRegistry ReturnsCallback 消息：{},回应码：{},回应信息：{},交换机：{},路由键：{}"
                    , msg, replyCode
                    , replyText, exchange
                    , routingKey);
        });
        rabbitTemplate.convertAndSend(RabbitMQConstantEnum.USER_INVITED_REGISTRY.getExchange()
                , RabbitMQConstantEnum.USER_INVITED_REGISTRY.getRoutingKey(), message, message1 -> {
                    message1.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT); // 设置消息持久化
                    return message1;
                }, correlationId);
        log.info("用户积分消息重试补发完成");
    }
}
